package com.example.springbooteasycode.zjrc.knowledgeSharing;

import java.util.Base64;

public class Base64Example {
    public static void main(String[] args) {
        // 将字符串转换为Base64字符串
        String originalString = "DA7F7E29CE508558";
        String base64EncodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
        System.out.println("Base64编码后的字符" +
                "串: " + base64EncodedString);

        // ----------
        String base64String = "NjUzNTIORUZGRDAxRTcxMQ==";
        // 将Base64字符串转换回byte[]
        byte[] decodedData = Base64.getDecoder().decode(base64String);
        System.out.println("解码后的byte[]: " + new String(decodedData));

        // 转为十六进制字符串
        // 将byte[]数组转换为十六进制字符串
        String hexString = byteArrayToHexString(decodedData);
        System.out.println("十六进制字符串: " + hexString);
    }

    public static String byteArrayToHexString(byte[] byteArray) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString().toUpperCase();
    }
}
